'use client'
// src/app/projects/[id]/_client.tsx
// Input: id (string)
// Output: page détail projet — rendue 100% client (évite SSR crash r3f)
// Rationale: wrapper dynamic ssr:false importé depuis page.tsx

import { useState } from 'react'
import Link from 'next/link'
import { notFound } from 'next/navigation'
import {
  BarChart3,
  FileDown,
  TriangleAlert,
  CircleCheck,
  CircleX,
  Info,
} from 'lucide-react'
import { motion } from 'framer-motion'

import { AppShell } from '@/components/shell/AppShell'
import { Breadcrumbs } from '@/components/shell/Breadcrumbs'
import { PageHeader } from '@/components/shell/PageHeader'
import { Button } from '@/components/ui/Button'
import { Badge } from '@/components/ui/Badge'
import { StatusDot } from '@/components/ui/StatusDot'
import { EmptyState } from '@/components/ui/EmptyState'
import { SceneWrapper } from '@/components/three/SceneWrapper'

import { ProjectMetaCard } from '@/components/projects/ProjectMetaCard'
import { SensorPanel } from '@/components/projects/SensorPanel'
import { StructureScene } from '@/components/projects/StructureScene'

import { projects } from '@/lib/mock/projects'
import { getSensorsForProject } from '@/lib/mock/sensors'
import { getAnomaliesForProject } from '@/lib/mock/anomalies'
import { relativeTime } from '@/lib/utils'
import type { Sensor } from '@/types'

const severityIcon = {
  info:     <Info size={13} strokeWidth={1.5} className="text-status-info" />,
  warning:  <TriangleAlert size={13} strokeWidth={1.5} className="text-status-warning" />,
  critical: <CircleX size={13} strokeWidth={1.5} className="text-status-danger" />,
}

const severityVariant = {
  info:     'info' as const,
  warning:  'warning' as const,
  critical: 'danger' as const,
}

const statusCounts = (sensors: Sensor[]) => ({
  online:      sensors.filter((s) => s.status === 'online').length,
  offline:     sensors.filter((s) => s.status === 'offline').length,
  warning:     sensors.filter((s) => s.status === 'warning').length,
  calibrating: sensors.filter((s) => s.status === 'calibrating').length,
})

export default function ProjectDetailClient({ id }: { id: string }) {
  const project = projects.find((p) => p.id === id)
  if (!project) notFound()

  const sensors = getSensorsForProject(id)
  const anomalies = getAnomaliesForProject(id)

  const [selectedId, setSelectedId] = useState<string | null>(null)
  const selectedSensor = sensors.find((s) => s.id === selectedId) ?? null
  const panelSensor = selectedSensor ?? sensors[0] ?? null
  const counts = statusCounts(sensors)

  const breadcrumbs = [
    { label: 'Projets', href: '/projects' },
    { label: project.name },
  ]

  return (
    <AppShell topbarContent={<Breadcrumbs items={breadcrumbs} />}>
      <PageHeader
        title={project.name}
        description={`${project.type === 'bridge' ? 'Pont' : 'Bâtiment'} · ${project.location}`}
        actions={
          <>
            <Link href={`/projects/${id}/analyses`}>
              <Button variant="primary" iconLeft={<BarChart3 size={14} strokeWidth={1.5} />}>
                Analyses
              </Button>
            </Link>
            <Button variant="secondary" iconLeft={<FileDown size={14} strokeWidth={1.5} />} disabled>
              Rapport PDF
            </Button>
          </>
        }
      />

      <ProjectMetaCard project={project} />

      <div className="flex gap-4 mb-6" style={{ height: 560 }}>
        <div className="flex-1 flex flex-col gap-2 min-w-0">
          <div className="flex-1 rounded-lg overflow-hidden border border-bg-border" style={{ minHeight: 0 }}>
            <SceneWrapper
              autoRotate
              autoRotateSpeed={0.4}
              enableInteraction
              style={{ width: '100%', height: '100%' }}
            >
              <StructureScene
                project={project}
                sensors={sensors}
                selectedId={selectedId}
                onSelect={setSelectedId}
              />
            </SceneWrapper>
          </div>

          <div className="flex items-center gap-4 px-1 py-1.5 rounded-md" style={{ background: '#111B28', border: '1px solid #1E2D3D' }}>
            <span className="text-caption text-text-muted">Capteurs :</span>
            {counts.online > 0 && (
              <span className="flex items-center gap-1.5">
                <StatusDot status="online" size="sm" />
                <span className="text-caption text-text-secondary">{counts.online} en ligne</span>
              </span>
            )}
            {counts.warning > 0 && (
              <span className="flex items-center gap-1.5">
                <StatusDot status="warning" size="sm" />
                <span className="text-caption text-text-secondary">{counts.warning} alerte</span>
              </span>
            )}
            {counts.offline > 0 && (
              <span className="flex items-center gap-1.5">
                <StatusDot status="offline" size="sm" />
                <span className="text-caption text-text-secondary">{counts.offline} hors ligne</span>
              </span>
            )}
            {counts.calibrating > 0 && (
              <span className="flex items-center gap-1.5">
                <StatusDot status="calibrating" size="sm" />
                <span className="text-caption text-text-secondary">{counts.calibrating} étalonnage</span>
              </span>
            )}
            <span className="ml-auto text-caption text-text-muted">
              Cliquer sur un capteur pour voir ses mesures
            </span>
          </div>
        </div>

        <div className="flex-shrink-0" style={{ width: 360, height: '100%' }}>
          {panelSensor ? (
            <SensorPanel sensor={panelSensor} onClose={selectedId ? () => setSelectedId(null) : null} />
          ) : (
            <div className="h-full rounded-lg border border-bg-border flex items-center justify-center" style={{ background: '#0F1620' }}>
              <EmptyState
                icon={<CircleCheck size={32} strokeWidth={1.5} className="text-text-muted" />}
                title="Aucun capteur"
                description="Ce projet n'a pas encore de capteurs configurés."
              />
            </div>
          )}
        </div>
      </div>

      {anomalies.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1], delay: 0.15 }}
        >
          <h2 className="text-h2 text-text-primary mb-3">Alertes récentes</h2>
          <div className="flex gap-3 overflow-x-auto pb-2">
            {anomalies.slice(0, 4).map((anomaly, idx) => (
              <motion.div
                key={anomaly.id}
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.35, ease: [0.16, 1, 0.3, 1], delay: 0.2 + idx * 0.05 }}
                className="flex-shrink-0"
                style={{ width: 280 }}
              >
                <div
                  className="rounded-lg p-4 flex flex-col gap-2 border transition-all duration-fast hover:border-accent-border"
                  style={{ background: '#0F1620', border: '1px solid #1E2D3D' }}
                >
                  <div className="flex items-center gap-2">
                    {severityIcon[anomaly.severity]}
                    <Badge variant={severityVariant[anomaly.severity]} size="xs">
                      {anomaly.severity === 'critical' ? 'Critique' : anomaly.severity === 'warning' ? 'Attention' : 'Info'}
                    </Badge>
                    {anomaly.acknowledged && (
                      <CircleCheck size={12} strokeWidth={1.5} className="text-text-muted ml-auto" />
                    )}
                  </div>
                  <span className="text-caption text-text-muted uppercase tracking-[0.05em]">
                    {anomaly.type.replace(/_/g, ' ')}
                  </span>
                  <p className="text-caption text-text-secondary leading-relaxed line-clamp-3">
                    {anomaly.description}
                  </p>
                  <span className="text-caption text-text-muted font-mono">
                    {relativeTime(anomaly.detectedAt)}
                  </span>
                </div>
              </motion.div>
            ))}
          </div>
        </motion.div>
      )}

      {anomalies.length === 0 && (
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.2 }}>
          <h2 className="text-h2 text-text-primary mb-3">Alertes récentes</h2>
          <div className="flex items-center gap-3 p-4 rounded-lg" style={{ background: '#0F1620', border: '1px solid #1E2D3D' }}>
            <CircleCheck size={16} strokeWidth={1.5} className="text-status-success" />
            <span className="text-body text-text-secondary">Aucune anomalie détectée sur ce projet.</span>
          </div>
        </motion.div>
      )}
    </AppShell>
  )
}
